﻿using Pegasus.Diagnostics;
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;

namespace Pegasus.Globalization
{
	/// <summary>
	/// 
	/// </summary>
	public class ResourceCache
	{
		private Hashtable m_resouceTable = new Hashtable();
		
		/// <summary>
		/// 
		/// </summary>
		public ResourceCache( Assembly assembly, string resourceNamespace )
		{
			// Check params
			ParamCode.AssertNotNull( assembly, "assembly" );
			ParamCode.AssertNotEmpty( resourceNamespace, "resourceNamespace" );

			LoadResouceManagers( assembly, resourceNamespace );
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public ResourceManager GetResourceManager( CultureInfo culture )
		{
			// Check params
			ParamCode.AssertNotNull( culture, "culture" );

			ResourceManager res = (ResourceManager) m_resouceTable[ culture.Name.ToLower() ];
			if( res == null )
			{
				res = (ResourceManager) m_resouceTable[ culture.TwoLetterISOLanguageName.ToLower() ];
				if( res == null )
				{
					res = (ResourceManager) m_resouceTable[ "default" ];
				}
			}

			return res;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="assembly"></param>
		/// <param name="resourceNamespace"></param>
		private void LoadResouceManagers( Assembly assembly, string resourceNamespace )
		{
			// Check params
			ParamCode.AssertNotNull( assembly, "assembly" );
			ParamCode.AssertNotEmpty( resourceNamespace, "resouceNamespace" );

			ArrayList resouceNames = new ArrayList();

			resourceNamespace = resourceNamespace.ToLower();
			foreach( string name in assembly.GetManifestResourceNames() )
			{
				string nameLower = name.ToLower();
				if( nameLower.StartsWith( resourceNamespace ) )
				{
					resouceNames.Add( name );
				}
			}

			foreach( string name in resouceNames )
			{
				ResourceManager res = new ResourceManager( assembly, name );
				m_resouceTable[ res.Culture.Name.ToLower() ] = res;

				if( res.Default )
				{
					m_resouceTable[ "default" ] = res;
				}
			}
		}
	}
}
